<script setup>
import { ref, defineOptions } from 'vue'
import TopTitle from "@/components/TopTitle.vue"
import { useRoute } from 'vue-router';
import { showToast } from 'vant';
import { typeChoose, newBookType } from "@/api/getAxios_2.ts";


// 获取类型
const categorys = ref([])
const tags = ref([])
const freeList = ref([])
const sortList = ref([])

const route = useRoute()
const name = ref('')
name.value = route.query.name
typeChoose().then((res) => {
    categorys.value = res.data.data.categorys
    tags.value = res.data.data.tags
    freeList.value = res.data.data.freeList
    sortList.value = res.data.data.sortList
})

// 选择类型（一开始）
let pageNo = ref('1');
let tag = ref('全部');
let sort = ref('fireValue');
let type = ref('全部');
let option = ref('全部');
const types = ref([])


// 定义四个ul的active
let active1 = ref(0)
let active2 = ref(0)
let active3 = ref(0)
let active4 = ref(0)
// newBookType(
//     pageNo.value, tag.value, sort.value, type.value, option.value
// ).then((res) => {
//     console.log(res);
// })
//     // types.value = res.data.data.list
//     // console.log(categorys.value);
//     // for (var i = 0; i < categorys.value.length; i++) {
//     //     if (route.query.alt == categorys.value[i].name) {
//     //         active1.value = i
//     //     }
//     // }
//     // if (route.query.alt != '悬疑灵异') {
//     //     active3.value = 0
//     //     active2.value = 0
//     //     active4.value = 0
//     // } else {
//     //     for (var i = 0; i < tags.value.length; i++) {
//     //         if (route.query.title == tags.value[i].name) {
//     //             active2.value = i
//     //         }
//     //     }
//     // }
// })

var myHeaders = new Headers();
myHeaders.append("c", "android/model:MuMu,SDK:Android6.0.1(API23)-huoxing/2.7.3/guanwang/000000000000000");
myHeaders.append("x-i", "e7ed69f043e48c5dd069b7a86d2913268cbdf5d92d4afc0f86107e26f40e7c4680683c82756ab7eeb002e5bff181eb8fdb5f3a818e6c8e86226faa198c7866de81ce843c1216e979ec3268d7d6c6a74a");
myHeaders.append("x-s", "7f967688bce71d15316450e757232689");
myHeaders.append("x-ssid", "");
myHeaders.append("set-cookie", "");
myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
myHeaders.append("content-type", "application/x-www-form-urlencoded");
myHeaders.append("Accept", "*/*");
myHeaders.append("Host", "api.m.hotread.com");
myHeaders.append("Connection", "keep-alive");

var urlencoded = new URLSearchParams();
urlencoded.append("pageNo", "1");
urlencoded.append("pageSize", "10");
urlencoded.append("channel", "1");
urlencoded.append("tag", "全部");
urlencoded.append("sort", "fireValue");
urlencoded.append("model", "4");
urlencoded.append("type", "全部");
urlencoded.append("option", "全部");

var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: urlencoded,
    redirect: 'follow'
};

fetch("/m1/story/listpageNew", requestOptions)
    .then(response => response.text())
    .then(result => {
        console.log(JSON.parse(result));
        types.value = JSON.parse(result).data.list
    })
    .catch(error => console.log('error', error));


// 切换类型并请求数据
const changeType = (e, index) => {
    // console.log(e.target);
    // newBookType().then((res) => {
    //     types.value = res.data.data.list
    // })
    // types.value = []
    for (var i = 0; i < e.target.parentNode.children.length; i++) {
        e.target.parentNode.children[i].classList.remove('active')
    }
    e.target.parentNode.children[index].classList.add('active')
    // categorys.value = document.querySelector('categorys').children.hasClass
    // categorys的每个li
    let num1 = document.querySelector('.categorys').children
    for (var j = 0; j < num1.length; j++) {
        if (num1[j].classList.contains("active")) {
            type.value = num1[j].innerText
            if (j == 0) {
                type.value = '全部'
            }
        }
    }
    // tags的每个li
    let num2 = document.querySelector('.tags').children
    for (var k = 0; k < num2.length; k++) {
        if (num2[k].classList.contains("active")) {
            tag.value = num2[k].innerText
            if (num2[k].innerText == '全部标签') {
                tag.value = '全部'
                break
            }
        }
    }
    // freeList的每个li
    let num3 = document.querySelector('.freeList').children
    for (var p = 0; p < num3.length; p++) {
        if (num3[p].classList.contains("active")) {
            if (p == 0) {
                option.value = '全部'
            } else {
                option.value = p - 1
            }
        }
    }

    let num4 = document.querySelector('.sortList').children
    for (var o = 0; o < num4.length; o++) {
        if (num4[o].classList.contains("active")) {
            if (o == 0) {
                sort.value = 'fireValue'
            } else if (o == 1) {
                sort.value = 'latestChapterTime'
            } else {
                sort.value = 'recommentTicket'
            }
        }
    }
    // console.log( pageNo.value, tag.value, sort.value, type.value, option.value);
    // newBookType(
    //     pageNo.value, tag.value, sort.value, type.value, option.value
    // ).then((res) => {
    //     // console.log(res);
    //     types.value = res.data.data.list
    // })

    var urlencoded = new URLSearchParams();
    urlencoded.append("pageNo", pageNo.value);
    urlencoded.append("pageSize", "10");
    urlencoded.append("channel", "1");
    urlencoded.append("tag", tag.value);
    urlencoded.append("sort", sort.value);
    urlencoded.append("model", "4");
    urlencoded.append("type", type.value);
    urlencoded.append("option", option.value);

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: urlencoded,
        redirect: 'follow'
    };

    fetch("/m1/story/listpageNew", requestOptions)
        .then(response => response.text())
        .then(result => {
            // console.log(JSON.parse(result));
            types.value = JSON.parse(result).data.list
        })
        .catch(error => console.log('error', error));

}

let flag = true
// 触底请求更多数据
const scrollHandler = (e) => {
    // console.log(types.value[types.value.length - 1]);
    const li = document.querySelector('.type1').children[types.value.length - 1]
    // console.log(li.offsetTop);
    // console.log(e.target.scrollTop + 680);
    if (e.target.scrollTop + 980 >= li.offsetTop && flag) {
        flag = false
        pageNo.value = (Number(pageNo.value) + 1).toString()

        var urlencoded = new URLSearchParams();
        urlencoded.append("pageNo", pageNo.value);
        urlencoded.append("pageSize", "10");
        urlencoded.append("channel", "1");
        urlencoded.append("tag", tag.value);
        urlencoded.append("sort", sort.value);
        urlencoded.append("model", "4");
        urlencoded.append("type", type.value);
        urlencoded.append("option", option.value);

        var requestOptions = {
            method: 'POST',
            headers: myHeaders,
            body: urlencoded,
            redirect: 'follow'
        };

        fetch("/m1/story/listpageNew", requestOptions)
            .then(response => response.text())
            .then(result => {
                // console.log(JSON.parse(result));
                // types.value = JSON.parse(result).data.list
                JSON.parse(result).data.list.forEach(o => types.value.push(o))
                flag = true
                if (JSON.parse(result).data.list.length == 0) {
                    showToast('已经到底啦！')
                    return
                }
            })
            .catch(error => console.log('error', error));
    }
}

//***************************************** */
// 返回顶部
const isShowBackTOP = ref(false)
const box = ref(null)
const backTop = () => {
    box.value.scrollTo({ top: 0, behavior: 'smooth' });
}


//***************************************** */

//***************************************** */

// 万和亿的换算
const getNumType = (num) => {
    if (num / 10000 >= 10000) {
        return (num / 100000000).toFixed(1) + '亿人气值'
    } else {
        return (num / 10000).toFixed(1) + '万人气值'
    }
}

//***************************************** */

</script>
<template>
    <div class="box" ref="box" @scroll="scrollHandler($event)">
    <!-- <div class="box" ref="box"> -->
        <TopTitle :flag="true" :name="name"></TopTitle>

        <div class="type">
            <ul class="categorys">
                <li v-for="(item, index) in categorys" :class="{ active: active1 == index }"
                    @click="changeType($event, index)">{{ item.name }}</li>
            </ul>
            <ul class="tags">
                <li v-for="(item, index) in tags" :class="{ active: active2 == index }" @click="changeType($event, index)">
                    {{
                        item.name }}</li>
            </ul>
            <ul class="freeList">
                <li v-for="(item, index) in freeList" :class="{ active: active3 == index }"
                    @click="changeType($event, index)">{{ item.name }}</li>
            </ul>
            <ul class="sortList">
                <li v-for="(item, index) in sortList" :class="{ active: active4 == index }"
                    @click="changeType($event, index)">{{ item.name }}</li>
            </ul>
        </div>
        <div class="city-msg">
            <ul class="type1">
                <li v-for="item in types" @click="$router.push(`/BookInfo?storyId=${item.id}`)" >
                    <div class="coverImg">
                        <img :src="item.smallCover" alt="">
                    </div>
                    <div class="msg">
                        <p class="name">{{ item.name }}</p>
                        <p class="detail">{{ item.introduce }}</p>
                        <p class="type2">
                            <span class="author-type">{{ item.authorName }} | {{ item.type }}</span>
                            <span class="fireValue">{{ getNumType(item.fireValue)}}</span>
                        </p>
                    </div>
                </li>
            </ul>
        </div>

        <div class="backTop" v-if="!isShowBackTOP">
            <span class="iconfont icon-fanhuidingbu1 back" @click="backTop"></span>
        </div>
    </div>
</template>

<style scoped lang='less'>
.box {
    background-color: #eee;
    height: 100vh;
    overflow: scroll;

    &::-webkit-scrollbar {
        display: none;
    }

    .recommend {
        height: 40vw;
        display: flex;
        background-color: #fff;
        justify-content: space-between;
        padding: 20px 0;
        margin-bottom: 10px;

        li {
            margin: 0 10px;
            width: 25vw;
            border-radius: 10px;

            img {
                box-shadow: 0px 15px 7px -11px rgba(0, 0, 0, .3);

                border-radius: 10px;
                width: 100%;
                height: 30vw;
            }

            p {
                text-align: center;
                font-size: 14px;
            }
        }
    }

    .type {
        margin-bottom: 10px;
        background-color: #fff;
        height: 60vw;
        display: flex;
        flex-direction: column;
        overflow: auto;

        &::-webkit-scrollbar {
            display: none;
        }

        ul {
            width: 1080px;
            display: flex;
            overflow: scroll;
            flex-wrap: nowrap;
            flex-direction: row;


            li {
                text-align: center;
                height: 30px;
                line-height: 30px;
                margin: 10px;
                padding: 0 10px;

                &.active {
                    border: 1px solid #db6974;
                    color: #db6974;
                    border-radius: 20px;
                }
            }
        }
    }

    .city-msg {
        background-color: #fff;
        margin-bottom: 15px;

        h1 {
            text-align: center;
            font-weight: bold;
            font-size: 22px;
            padding: 20px 0px;
            position: relative;
        }

        ul.type1 {
            display: flex;
            flex-direction: column;

            li {
                padding: 10px;
                height: 40vw;
                display: flex;

                .coverImg {

                    border-radius: 10px;
                    width: 30vw;
                    height: 40vw;

                    img {
                        border-radius: 10px;
                        box-shadow: 0px 15px 7px -11px rgba(0, 0, 0, .3);

                        width: 100%;
                        height: 100%;
                    }
                }

                .msg {
                    text-align: center;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;
                    width: 68vw;
                    margin-left: 10px;

                    .name {
                        font-size: 18px;
                    }

                    .detail {
                        display: -webkit-box;
                        text-align: center;
                        -webkit-line-clamp: 2;
                        -webkit-box-orient: vertical;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        color: #939296;
                        font-size: 14px;
                    }

                    .type2 {

                        color: #939296;
                        font-size: 12px;

                        .fireValue {
                            margin-left: 20px;
                            color: #ccae59;
                        }
                    }


                }

            }
        }
    }

    .backTop {
        height: 50px;
        position: fixed;
        bottom: 50px;
        right: 0;
        width: 50px;

        // font-size: 30px;
        .back {
            font-size: 30px;
            color: aquamarine;
        }
    }
}
</style>